﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Product.Wpf.Models;
using Product.Wpf.Models.Response;
using Product.Wpf.ViewModels.Page;
using Product.Wpf.Views.Page;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;

namespace Product.Wpf.ViewModels
{
   partial class  MainWindowViewModel : ObservableObject
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private const string ApiUrl = "https://localhost:7080/api/Product/GetProductList";
        private string APiGetProductBycategory = "https://localhost:7080/api/Product/GetProductByCategory/";
        private string APiGetProductById = "https://localhost:7080/api/Product/GetProductById/";
        private string APiGetProductSearchSuggestion = "https://localhost:7080/api/Product/GetProductSearchSuggestions/";
        //
        private string APiGetProductBySearch = "https://localhost:7080/api/Product/GetProductBySearch/";
        private string SelectCategory;


        [ObservableProperty]
        ObservableCollection<Category> _categories = new ObservableCollection<Category>();

        [ObservableProperty]
        List<ProductInfo> products = new List<ProductInfo>();



        [ObservableProperty]
        private ProductInfo product;
        [ObservableProperty]
        private decimal originalPrice;
        [ObservableProperty]
        private decimal price;

        [ObservableProperty]
        private string searchSuggestion;

        // 建议列表可见性
        [ObservableProperty]
        private Visibility _isSuggestionListVisible = Visibility.Collapsed;

        [ObservableProperty]
        ObservableCollection<string> suggestion= new ObservableCollection<string>();

        // 选中的建议项
        [ObservableProperty]
        private string _selectedSuggestion;

        [ObservableProperty]
        object pageContent;

        // 防抖计时器
        private readonly System.Windows.Threading.DispatcherTimer _debounceTimer;
        public   MainWindowViewModel()
        {
            PageContent = new ListProductPage();

            GetCategoryAsync();

            // 初始化防抖计时器（300毫秒）
            _debounceTimer = new System.Windows.Threading.DispatcherTimer();
            _debounceTimer.Interval = TimeSpan.FromMilliseconds(300);
            _debounceTimer.Tick += DebounceTimer_Tick;

        }

        private void DebounceTimer_Tick(object? sender, EventArgs e)
        {
            _debounceTimer.Stop();
            UpdateSuggestions();
        }

        private async void UpdateSuggestions()
        {
            if (string.IsNullOrWhiteSpace(SearchSuggestion))
            {
                Suggestion.Clear();
                IsSuggestionListVisible = Visibility.Collapsed;
                return;
            }

            if (SearchSuggestion != null)
            {
                var url = APiGetProductSearchSuggestion + SearchSuggestion;
                try
                {
                    var responseapi = await _httpClient.GetAsync(url);
                    if (responseapi.IsSuccessStatusCode)
                    {
                        var jsonResponse = await responseapi.Content.ReadAsStringAsync();

                        // 解析JSON
                        var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        };

                        var apiResponse = JsonSerializer.Deserialize<SearchSuggestionResponse>(jsonResponse, options);
                        if (apiResponse?.Success == true && apiResponse.Data != null)
                        {
                            Suggestion = apiResponse.Data;
                        }


                    }
                    else
                    {

                        return;
                    }


                }
                catch (Exception)
                {

                    throw;
                }

            }


            // 根据是否有建议控制显示状态
         IsSuggestionListVisible = Suggestion.Any()
                ? Visibility.Visible
                : Visibility.Collapsed;
           
        }



        [RelayCommand]
        private async void GetProductList(Category obj)
        {
            if (obj.Name == "全部" && obj != null)
            {
                try
                {
                    var responseapi = await _httpClient.GetAsync(ApiUrl);
                    if (responseapi.IsSuccessStatusCode)
                    {
                        var jsonResponse = await responseapi.Content.ReadAsStringAsync();

                        // 解析JSON
                        var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        };

                        var apiResponse = JsonSerializer.Deserialize<ProductResponse>(jsonResponse, options);
                        if (apiResponse?.Success == true && apiResponse.Data != null)
                        {
                            Products = apiResponse.Data;
                        }

                    }
                }
                catch (Exception)
                {

                    throw;
                }
            }
            else
            {

                try
                {
                    SelectCategory = obj.Url;
                    var url = APiGetProductBycategory + SelectCategory;
                    var responseapi = await _httpClient.GetAsync(url);
                    if (responseapi.IsSuccessStatusCode)
                    {
                        var jsonResponse = await responseapi.Content.ReadAsStringAsync();

                        // 解析JSON
                        var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        };

                        var apiResponse = JsonSerializer.Deserialize<ProductResponse>(jsonResponse, options);
                        if (apiResponse?.Success == true && apiResponse.Data != null)
                        {
                            Products = apiResponse.Data;
                        }

                    }
                }
                catch (Exception)
                {

                    throw;
                }
            }




        }

        private async void GetCategoryAsync()
        {
            try
            {
                var responseapi = await _httpClient.GetAsync("https://localhost:7080/api/Category/GetCategories");
                if (responseapi.IsSuccessStatusCode)
                {
                    var jsonResponse = await responseapi.Content.ReadAsStringAsync();

                    // 解析JSON
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };

                    var apiResponse = JsonSerializer.Deserialize<CategoryResponse>(jsonResponse, options);
                    if (apiResponse?.Success == true && apiResponse.Data != null)
                    {

                        Categories = apiResponse.Data;
                        Categories.Insert(0, new Category { Name = "全部" });

                    }


                }
                else
                {

                    return;
                }


            }
            catch (Exception)
            {

                throw;
            }
        }


        [RelayCommand]
        private async void NavigateToProductDetail(Models.ProductInfo product)
        {
            var page = new ProductDetialPage();
          
            PageContent=page;
            GetProductAsync(product.Id);
        }


        private async void GetProductAsync(Guid id)
        {
            var url = APiGetProductById + id;
            var responseapi = await _httpClient.GetAsync(url);
            if (responseapi.IsSuccessStatusCode)
            {
                var jsonResponse = await responseapi.Content.ReadAsStringAsync();

                // 解析JSON
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };

                var apiResponse = JsonSerializer.Deserialize<ProductDetailResponse>(jsonResponse, options);
                if (apiResponse?.Success == true && apiResponse.Data != null)
                {
                    Product = apiResponse.Data;
                }

            }
        }

        [RelayCommand]
        private async void GoBack(object obj)
        {
           var page=new ListProductPage();
            PageContent=page;
        }

        [RelayCommand]
        private async void SelectVariant(Variant item)
        {
            OriginalPrice = item.OriginalPrice;
            Price = item.Price;
        }

        async partial void OnSearchSuggestionChanged(string? Value)
        {
            
            // 重置防抖计时器
            _debounceTimer.Stop();
            _debounceTimer.Start();
            // 如果文本为空则隐藏建议
            if (string.IsNullOrWhiteSpace(Value))
            {
                IsSuggestionListVisible = Visibility.Collapsed;
            }
            
        }

        // 部分方法：当选中建议项时自动调用
        partial void OnSelectedSuggestionChanged(string value)
        {
           
            if (value != null)
            {
                // 设置搜索文本为选中的建议项
                SearchSuggestion = value;

                // 隐藏建议列表
                IsSuggestionListVisible = Visibility.Collapsed;

                // 执行搜索
                UpdateSuggestions();
            }
        }

        [RelayCommand]
        private async void GetProductBySearch()
        {
            if (!string.IsNullOrWhiteSpace(SearchSuggestion))
            {
                Products.Clear();
                var url = APiGetProductBySearch + SearchSuggestion;
                try
                {
                    var responseapi = await _httpClient.GetAsync(url);
                    if (responseapi.IsSuccessStatusCode)
                    {
                        var jsonResponse = await responseapi.Content.ReadAsStringAsync();

                        // 解析JSON
                        var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        };

                        var apiResponse = JsonSerializer.Deserialize<ProductResponse>(jsonResponse, options);
                        if (apiResponse?.Success == true && apiResponse.Data != null)
                        {

                            Products = apiResponse.Data;
                            
                        }


                    }
                    else
                    {

                        return;
                    }


                }
                catch (Exception)
                {

                    throw;
                }

            }
        }
    }
}
